package com.szeastroc.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szeastroc.base.service.BaseServiceImpl;
import com.szeastroc.bean.system.SystemResource;
import com.szeastroc.bean.system.SystemRole;
import com.szeastroc.bean.system.SystemUser;
import com.szeastroc.mapper.system.SystemUserMapper;
import com.szeastroc.service.system.SystemResourceService;
import com.szeastroc.service.system.SystemRoleService;
import com.szeastroc.service.system.SystemUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SystemUserServiceImpl extends BaseServiceImpl<SystemUser> implements SystemUserService {

	@Autowired
	private SystemUserMapper systemUserMapper;

	@Autowired
	private SystemRoleService systemRoleService;

	@Autowired
	private SystemResourceService systemResourceService;

	public SystemUser selectByUserName(String userName){
		SystemUser user = systemUserMapper.selectByUserName(userName);
		List<SystemRole> roles = systemRoleService.selectRolesByUserId(user.getId());
        user.setRoles(roles);
        String ids = "";
		for (SystemRole role : roles) {
            ids += role.getId() + ",";
		}
		if(StringUtils.isNoneBlank(ids)){
            List<SystemResource> resources = systemResourceService.getSystemResourceParentByRoleIds(ids.substring(0,ids.length()-1));
            for (SystemResource resource : resources) {
                List<SystemResource> rs = systemResourceService.getSystemResourceByParentId(resource.getId());
                resource.setSysytemResources(rs);
            }
            user.setResources(resources);
        }
		return user;
	}

	public PageInfo<SystemUser> selectPage(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<SystemUser> list = systemUserMapper.selectUsers();
        PageInfo<SystemUser> pageInfo = new PageInfo<SystemUser>(list);
        return pageInfo;
	}

	@Transactional
    public void updateUserRole(Integer userId,Integer roleId){
        systemUserMapper.updateUserRole(userId, roleId);
    }

}
